import 'dart:convert';
import 'package:base_flutter/base_flutter.dart' as b;
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:ls_work/a_elder/models/waiting_right_entity.dart';
import 'package:ls_work/a_yyt/models/elder_time_line_entity.dart';
import 'package:ls_work/a_yyt/models/pending_selected_group_entity.dart';
import 'package:ls_work/a_yyt/page/pending_single_group_page.dart';
import 'package:ls_work/a_yyt/widget/client_time_cell.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:date_format/date_format.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/click_item.dart';

import '../../util/flat_button.dart';



///评估审核
class PendingBizType2010 extends StatefulWidget {
  final WaitingRighInfo? info;
  final VoidCallback? callBack;
  PendingBizType2010({Key? key, this.info, this.callBack});
  @override
  _PendingBizType2010State createState() => _PendingBizType2010State();
}

class _PendingBizType2010State extends State<PendingBizType2010> {
  TextEditingController textFieldEditer = TextEditingController();
  List<TimeLinesInfo> timeLineList = [];
  List<List<PendingSelectedGroupEntity>> sortList = [];
  List<PendingSelectedGroupEntity> sortContentList = [];
  // int _groupValue = 1;
  String _selectedDateTime = '';
  DateTime _selectedDate = DateTime.now(); //当前选中的日期
  int nurseLevelId = 0;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      fectElderTimeLine();
      _getAllByCurBranchWithUsers();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('整合性计划分配'),
        elevation: 0.5,
      ),
      body: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          SingleChildScrollView(
            padding: EdgeInsets.fromLTRB(15, 30, 15, 80),
            child: Column(
              // height: ScreenUtil.getScreenH(context),
              // width: ScreenUtil.getScreenW(context),
              // padding: EdgeInsets.fromLTRB(30, 30, 30, 80),
              // child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text.rich(TextSpan(children: [
                  TextSpan(
                    text: '   长者：',
                    style: TextStyles.textGray18,
                  ),
                  TextSpan(
                    text: '${widget.info?.elderName ?? ''}',
                    style: TextStyles.textDark18,
                  ),
                ])),
                Gaps.vGap16,
                Gaps.vGap10,
                Text.rich(TextSpan(children: [
                  TextSpan(
                    text: '   类型：',
                    style: TextStyles.textGray18,
                  ),
                  TextSpan(
                    text: '${widget.info?.bizParams?.serviceItem ?? ''}',
                    style: TextStyles.textDark18,
                  ),
                ])),
                Gaps.vGap10,
                ClickItem(
                  title: '*处理截止日期：',
                  titleStyle: TextStyles.textGray18,
                  contentStyle: TextStyles.textDark18,
                  content: '$_selectedDateTime',
                  onTap: _bottomDateTimeSheetAlert,
                ),
                Gaps.vGap16,
                Text(
                  '   照护目标',
                  style: TextStyles.textGray18,
                ),
                Container(
                  padding: EdgeInsets.all(20),
                  color: Colors.white,
                  alignment: Alignment.topLeft,
                  height: 150,
                  child: TextField(
                    controller: textFieldEditer,
                    maxLines: 5,
                    maxLength: 150,
                    autofocus: false,
                    decoration: InputDecoration(
                      hintText: "请输入内容",
                      hintMaxLines: 20,
                      fillColor: Colours.bg_color,
                      filled: true,
                      border: InputBorder.none,
                    ),
                  ),
                ),
                Gaps.vGap16,
                Text(
                  '   选择执行组',
                  style: TextStyles.textGray18,
                ),
                Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: sortList.map((e) {
                    int index = sortList.indexOf(e);
                    return ClickItem(
                      title: '${e.first.serviceTypeName}',
                      titleStyle: TextStyles.textGray18,
                      contentStyle: TextStyles.textDark18,
                      content: '${sortContentList[index].name ?? ''}',
                      onTap: () {
                        AppNavigator.push(
                          context,
                          PendingSingleGroupPage(
                            sortList: sortList[index],
                            callBack: (info) {
                              setState(() {
                                sortContentList[index] = info;
                              });
                            },
                          ),
                        );
                      },
                    );
                  }).toList(),
                ),
                Gaps.vGap16,
                Gaps.vGap16,
                Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: timeLineList.map((e) {
                    int index = timeLineList.indexOf(e);
                    return ClientTimeCell(
                      count: timeLineList.length,
                      info: timeLineList[index],
                    );
                  }).toList(),
                ),
              ],
            ),
          ),
          Positioned(
            bottom: 30,
            left: 0,
            right: 0,
            child: SizedBox(
              width: ScreenUtil.getScreenW(context),
              height: 50,
              child: FlatsButton(
                color: Colors.blue,
                highlightColor: Colors.blue[700]!,
                
                child: Text("提交"),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25.0)),
                onPressed: _send,
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///处理截止时间
  _bottomDateTimeSheetAlert() {
    DatePicker.showDatePicker(
      context,
      minDateTime: DateTime.now(),
      maxDateTime: DateTime.parse("2099-01-01 00:00:00"),
      initialDateTime: DateTime.parse(formatDate(_selectedDate,
          [yyyy, "-", mm, "-", "dd", " ", HH, ":", nn, ":", ss])),
      dateFormat: "yyyy年MM月dd日    EEE,H时:mm分",
      locale: DateTimePickerLocale.zh_cn,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定'),
      ),
      pickerMode: DateTimePickerMode.datetime, // show TimePicker
      onConfirm: (dateTime, List<int> index) {
        setState(() {
          _selectedDate = dateTime;
          _selectedDateTime =
              DateUtil.formatDate(dateTime, format: 'yyyy-MM-dd HH:mm:ss');
        });
      },
    );
  }

  void fectElderTimeLine() {
    var map = {
      'traceType': 100,
      'relationId': widget.info?.bizId,
      'customerId': widget.info?.customerId,
    };

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.elderTimeLine, data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            TimeLineEntity model = TimeLineEntity.fromJson(map['data']);
            // print('🍎 - length - ${model.rows.length}');
            if ((model.rows??[]).length >= 0) {
              setState(() {
                timeLineList = model.rows??[];
              });
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///获取分组
  void _getAllByCurBranchWithUsers() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(
          HttpApi.getAllByCurBranchWithUsers,
        )
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            PendingSelectedGroupSection model =
                PendingSelectedGroupSection.fromJson(map);
            var newMap = {};
            List<List<PendingSelectedGroupEntity>> sectionList = [];
            for (var i = 0; i < (model.data??[]).length; i++) {
              PendingSelectedGroupEntity info = model.data![i];
              if (newMap[info.serviceTypeName] == null) {
                List<PendingSelectedGroupEntity> tempList = [];
                tempList.add(info);
                sectionList.add(tempList);
                newMap[info.serviceTypeName] = info;
              } else {
                for (var j = 0; j < sectionList.length; j++) {
                  PendingSelectedGroupEntity dj = sectionList[j].first;
                  if (dj.serviceTypeName == info.serviceTypeName) {
                    sectionList[j].add(info);
                    break;
                  }
                }
              }
            }
            setState(() {
              sortList.addAll(sectionList);
              sortList.forEach((element) {
                sortContentList.add(PendingSelectedGroupEntity());
              });
            });
            // print('🍎 - sortListlength - ${sortList.length}');
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///提交
  void _send() {
    if (TextUtil.isEmpty(_selectedDateTime)) {
      Toast.show('请选择处理截止日期');
      return;
    }
    var map = {
      'id': widget.info?.bizId,
      'customerId': widget.info?.customerId,
      'launchType': widget.info?.bizParams?.launchType,
      'closeDate': _selectedDateTime,
    };
    if (!TextUtil.isEmpty(textFieldEditer.text)) {
      map['serviceGoal'] = textFieldEditer.text;
    }
    for (PendingSelectedGroupEntity info in sortContentList) {
      if (info.postCode != null && info.postCode == '109106') {
        map['jiehuGroupId'] = info.id;
      }
      if (info.postCode != null && info.postCode == '109107') {
        map['huliGroupId'] = info.id;
      }
      if (info.postCode != null && info.postCode == '109108') {
        map['shegongGroupId'] = info.id;
      }
      if (info.postCode != null && info.postCode == '109109') {
        map['yingyangGroupId'] = info.id;
      }
      if (info.postCode != null && info.postCode == '109110') {
        map['kangfuGroupId'] = info.id;
      }
    }
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.servicePlanElderSend,
            data: {'jsonStr': jsonEncode(map)},options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          if(widget.callBack!=null){
            widget.callBack!();
          }

          Navigator.pop(context);
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
